package com.honey.serializable;

import java.util.List;

import com.honey.compilation.java.AbstractJavaCompilation;
import com.honey.compilation.java.Field;
import com.honey.compilation.java.Method;
import com.honey.core.types.FullyQualifiedJavaType;

public abstract class BaseSerializableObjectMethod implements SerializableObjectMethod {
	
	/* (non-Javadoc)
	 * @see com.honey.json.append.AppendToJsonObjectMethod#appendJsonMethod(com.honey.compilation.java.AbstractJavaCompilation)
	 */
	@Override
	public void appendJsonMethod(AbstractJavaCompilation abstractJavaCompilation) {
		List<Field> fields  =   abstractJavaCompilation.getFields() ;
		Method jsonMethod = new Method("toJsonObject", getJsonObjectType());
		StringBuilder sb = new StringBuilder()
		.append(getJsonObjectType().getShortName() )
		.append(" answer = new ")
		.append(getJsonObjectType().getShortName())
		.append("( )");
		jsonMethod.addBodyLine(sb.toString());
		for(Field field : fields  ){
			if(field.getDecoration().isFinal() || field.getDecoration().isStatic()){
				continue;
			}
			sb.setLength(0);
			sb.append("answer.")
			.append( getAppendMethodName() ).append("(\"")
			.append(field.getName())
			.append("\",").append(getValue(field))
			.append(")");
			jsonMethod.addBodyLine(sb.toString());
		}
		jsonMethod.addBodyLine("return answer");
		abstractJavaCompilation.addMethod(jsonMethod);
	}
	
	public StringBuilder getValue(Field field ){
		FullyQualifiedJavaType type = field.getType();
		StringBuilder answer = new StringBuilder();
		if(type.isPrimitive() ){
			answer.append(field.getName());
		} else if("Date".equals(type.getShortName())  )  {
			answer.append(field.getName() )
			.append(" == null ? \"\" : ")
			.append(field.getName())
			.append(".getTime()");
		}else {
			answer.append(field.getName() )
			.append(" == null ? \"\" : ").append(field.getName());
		}
		return answer;
	}
	
	/**
	 * 获取json类型 
	 * @return
	 */
	public  FullyQualifiedJavaType getJsonObjectType(){
		return null;
	}
	
	
	/**
	 * 获取json对象中追加值的方法
	 * @return
	 */
	public  String getAppendMethodName(){
		
		return null;
	}
	
	
}
